// pages/reminder/index.js
import http from '../../utils/request';  // ✅ 改用封装后的请求模块

Page({
    data: {
      customerList: [],
      activeId: null,
      selectedCustomer: null,
      smsContent: '',
      isSending: false,
      employeeNumber: '',
      userName: '',     // 新增用户名存储字段
      smsCharCount: 0,   // 新增字数统计字段
      scrollHeight: 500,    // 初始滚动高度
      keyboardHeight: 0     // 键盘高度
    },

    // ====================== 生命周期方法 ======================
    onLoad() {
      // 监听键盘高度变化
      wx.onKeyboardHeightChange(res => {
        this.setData({ keyboardHeight: res.height });
        this.adjustScrollHeight();
      });
      this.adjustScrollHeight();
    },
  
    // 动态调整数据区域高度
    adjustScrollHeight() {
      const systemInfo = wx.getWindowInfo();
      const windowHeight = systemInfo.windowHeight;
      const newHeight = windowHeight - this.data.keyboardHeight - 270; // 270rpx为底部区域预估高度
      this.setData({
        scrollHeight: newHeight > 200 ? newHeight : 200
      });
    },
  
    // 输入框聚焦时处理
    onInputFocus() {
      if (wx.getDeviceInfo().platform === 'ios') {
        setTimeout(() => {
          wx.pageScrollTo({
            scrollTop: 99999, // 强制滚动到底部
            duration: 300
          });
        }, 300);
      }
    },
  
    // 输入框失焦时处理
    onInputBlur() {
      this.setData({ keyboardHeight: 0 });
      this.adjustScrollHeight();
    },
  
    onShow() {
      this.checkLoginStatus();
    },

    // ====================== 登录状态检查 ======================  
    checkLoginStatus() {
      try {
        const userInfo = wx.getStorageSync('userInfo');
        
        // 新增用户名读取逻辑
        const userName = userInfo.name || '未知用户'; // 添加默认值

        if (!userInfo?.employee_number) {
          this.showLoginAlert();
          return;
        }
        
        this.setData(
          { employeeNumber: userInfo.employee_number.trim(),
            userName: userName // 新增用户名存储
          },
          () => this.loadCustomerData()
        );
        
      } catch (error) {
        console.error('存储读取失败:', error);
        this.showLoginAlert();
      }
    },
  
    showLoginAlert() {
        wx.showModal({
          title: '未登录',
          content: '请先登录后再使用该功能',
          confirmText: '去登录',
          cancelText: '返回首页', // 明确提示取消操作的含义
          success: (res) => {
            if (res.confirm) {
              wx.reLaunch({ url: '/pages/user/user' });
            } else if (res.cancel) {
              // 增加页面堆栈判断防止报错
              if (getCurrentPages().length > 1) {
                wx.navigateBack({ delta: 1 }); // 返回上一页
              } else {
                wx.reLaunch({ url: '/pages/home/home' }); // 无上一页时回首页
              }
            }
          },
          fail: (err) => {
            console.error('弹窗调用失败:', err);
          }
        });
      },

    // ====================== 数据加载接口改造 ======================
    async loadCustomerData() {
      if (!this.data.employeeNumber) return;
  
      wx.showLoading({ title: '加载中...' });
      try {
        // ============== 接口改造开始 ==============
        const res = await http.get('/pending_sms_customers', {
          employee_number: this.data.employeeNumber
        });
        // ============== 接口改造结束 ==============

        console.log('[DEBUG] 原始响应数据:', res);

        // ✅ 适配新的响应结构
        if (res?.status !== 'success' || !res.data) {
          throw new Error(res?.message || '数据加载失败');
        }

        const rawData = res.data || [];
        console.log('处理前的原始数据:', rawData);

        const customerList = rawData.map(item => ({
          id: item.id,
          name: item.name || '未知客户',
          phone: item.phone?.toString() || '暂无号码',
          expire_date: this.formatDate(item.expire_date),
          amount: item.amount ? Number(item.amount).toFixed(2) : '0.00',
          formattedPhone: this.formatPhoneNumber(item.phone), // 格式化电话号码
          formattedAmount: this.formatAmount(item.amount),    // 格式化金额
          sms_reminded: item.sms_reminded || 0
        }));

        console.log('处理后的客户列表:', customerList);
        this.setData({ customerList });
  
      } catch (error) {
        console.error('数据加载失败:', error);
        wx.showToast({ 
          title: error.message || '数据加载失败',
          icon: 'none',
          duration: 3000
        });
      } finally {
        wx.hideLoading();
      }
    },
  
    // ====================== 数据格式化方法 ======================
    formatDate(dateStr) {
      try {
        return dateStr ? dateStr.split('T')[0] : '无日期';
      } catch {
        return '日期格式错误';
      }
    },
  
    handleSelect(e) {
      const item = e.currentTarget.dataset.item;
      if (!item) return;
  
      const gender = this.guessGender(item.name);
      const content = `您好，${item.name}${gender}，我是您的客户经理${this.data.userName}，您的定期存款${item.amount}元，将于${item.expire_date}到期，请及时来我网点办理转存业务。`;
      
      
      this.setData({
        activeId: item.id,
        selectedCustomer: item,
        smsContent: content
      });
    },
  
    guessGender(name) {
      if (!name) return '先生';
      const lastChar = name.slice(-1);
      return ['女', '姐', '妹'].includes(lastChar) ? '女士' : '先生';
    },

    // ====================== 短信内容处理 ======================
    handleContentChange(e) {
      const content = e.detail.value;
      const charCount = content.length;
      
      // 新增字数提示逻辑
      if (charCount === 70) {
        wx.showToast({
          title: '最多输入70个字',
          icon: 'none',
          duration: 2000
        });
      }
  
      this.setData({
        smsContent: content,
        smsCharCount: charCount
      });
    },
  
    // ====================== 短信发送逻辑 ======================
    async handleSend() {
      if (!this.validateSendConditions()) return;
  
      this.setData({ isSending: true });
      
      try {
        await Promise.all([
          this.sendSMS(),
          this.updateSMSStatus()
        ]);
        
        wx.showToast({ title: '发送成功' });
        this.refreshData();
      } catch (error) {
        console.error('[ERROR] 发送流程失败:', error);
        wx.showToast({ 
          title: error.message || '发送失败',
          icon: 'none',
          duration: 3000
        });
      } finally {
        this.setData({ isSending: false });
      }
    },
  
    validateSendConditions() {
      if (!this.data.employeeNumber) {
        this.showLoginAlert();
        return false;
      }
      
      if (!this.data.selectedCustomer) {
        wx.showToast({ title: '请先选择客户', icon: 'none' });
        return false;
      }

      if (this.data.smsContent.length > 70) {
        wx.showToast({
          title: '内容超过70字限制',
          icon: 'none'
        });
        return false;
      }
  
      return true;
    },
  
    async sendSMS() {
      console.log('[DEBUG] 短信参数:', {
        phoneNumber: this.data.selectedCustomer.phone,
        content: this.data.smsContent
      });
        
      return new Promise((resolve, reject) => {
        console.log('用户手机号为：', this.data.selectedCustomer.phone);
        wx.sendSms({
          phoneNumber: this.data.selectedCustomer.phone,
          content: this.data.smsContent,
          success: resolve,
          fail: (err) => reject(new Error(`短信发送失败: ${err.errMsg}`))
        });
      });
    },

    // ====================== 状态更新接口改造 ======================
    async updateSMSStatus() {
      try {
        // ============== 接口改造开始 ==============
        const res = await http.post('/update_sms_status', {
          customer_id: this.data.activeId,
          employee_number: this.data.employeeNumber
        });
        // ============== 接口改造结束 ==============
        
        console.log('[DEBUG] 状态更新响应:', res);
        if (res?.status !== 'success') {
          throw new Error(res?.message || '状态更新失败');
        }
      } catch (error) {
        console.error('[ERROR] 状态更新失败:', error);
        throw new Error(`状态更新失败: ${error.message}`);
      }
    },

    // ====================== 工具方法 ======================
    formatPhoneNumber(phone) {
      if (!phone || typeof phone !== 'string' || phone.length !== 11) {
        return '无效号码';
      }
      return `${phone.slice(0,3)}***${phone.slice(-3)}`;
    },
    
    formatAmount(amount) {
        const num = Number(amount);
        if (isNaN(num)) return '0.0万';
        
        if (num >= 100000000) {
          return `${(num / 100000000).toFixed(1)}亿`;
        }
        if (num >= 10000) {
          return `${(num / 10000).toFixed(1)}万`;
        }
        return `${num.toFixed(0)}元`;
      },

    showFullPhone(e) {
      const phone = e.currentTarget.dataset.phone;
      wx.showModal({
        title: '完整号码',
        content: phone,
        showCancel: false
      });
    },
     
    refreshData() {
      this.setData({
        activeId: null,
        selectedCustomer: null,
        smsContent: ''
      });
      this.loadCustomerData();
    }
});